package thread2;

class MyBlockingQueue {
    private int[] items = new int[1000];
    private int size = 0;
    private int head = 0;
    private int tail = 0;

    private Object locker = new Object();

    public void put(int val) throws InterruptedException {
        synchronized (locker) {
            if (size == items.length) {
                // return;
                locker.wait();
            }
            items[tail] = val;
            tail++;
            if (tail >= items.length) {
                tail = 0;
            }
            size++;
            locker.notify();//唤醒take
        }
    }

    public Integer take() throws InterruptedException {
        synchronized (locker) {
            if (size == 0) {
                locker.wait();
//                return null;
            }
            int ret = items[head];
            head++;
            if (head >= items.length) {
                head = 0;
            }
            size--;
            locker.notify();//唤醒put
            return ret;
        }
    }
}

public class Test1 {
    private static MyBlockingQueue queue = new MyBlockingQueue();

    public static void main(String[] args) throws InterruptedException {
        Thread producer = new Thread(() -> {
            int n = 1;
            while (true) {
                try {
                    queue.put(n);
                    System.out.println("生产者生产了：" + n);
                    n++;
                    //Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            }
        });
        producer.start();

        Thread customer = new Thread(() -> {
            while (true) {
                try {
                    int n = queue.take();
                    System.out.println("消费者消费了 " + n);
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        customer.start();
    }
}
